package com.hup.utils.io.batch.function;

import com.hup.utils.io.batch.BaseBatch;
import com.hup.utils.io.batch.SimpleBatchResp;
import com.hup.utils.io.batch.constant.WinServiceStartType;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;

/**
 * 修改指定服务的启动类型
 *
 * @author hugan
 * @date 2020/1/22
 */
@Log4j2
public class ScConfigServiceStartType implements BaseBatch<SimpleBatchResp> {

    private String serviceName;
    private WinServiceStartType startType;

    /**
     * @param startType notNull
     */
    public ScConfigServiceStartType(String serviceName, WinServiceStartType startType) {
        this.serviceName = serviceName;
        this.startType = startType;
    }

    /**
     * AUTO(自动) DEMAND(手动) DISABLED(禁用)
     * <boot|system|auto|demand|disabled|delayed-auto>
     * <p>
     * 'sc config 服务名 start= [xx]', 等号后要有空格
     * sc config  MySQL5.5 start= DISABLED
     *
     * @apiNote 不同版本号的系统可能会有差异
     */
    @Override
    public String cmd() {
        return "sc config \"" + serviceName + "\" start= " + startType.scConfigTypeCmd;
    }

    @Override
    public String desc() {
        return "指令设置服务[" + serviceName + "]为[" + startType.desc + "]";
    }

    @Override
    public SimpleBatchResp parse(ArrayList<String> lstResp) {
        log.debug("resp.size={}", lstResp.size());
        //log.info("[{}]", TextUtil.getLineWrap(lstResp));

        if (lstResp.get(0).contains("失败")) {
            String errMsg;
            if (!lstResp.get(2).contains("参数错误")) {
                errMsg = lstResp.get(2);
            } else {
                /*
                对于类似"OneSyncSvc_b90a7"这样的流氓,
                    其主体服务是neSyncSvc,后缀应该是实例id,会一直变化
                    服务管理器中,不会显示主体服务,
                执行命令时,服务名是不带后缀时,才会执行成功,
                    否则一律提示参数错误,
                    但只禁用主体服务,不禁用实例,则实例是一直在运行的
                所以只能通过注册表的方式禁用服务(注册表中可以看到[主体和实例服务]的两个独立项)
                 */
                errMsg = lstResp.get(2) + "\n" + cmd();
            }
            return SimpleBatchResp.fail(this, errMsg);
        }


        if (!lstResp.get(0).contains("成功")) {
            return SimpleBatchResp.fail(this, lstResp);
        }

        return SimpleBatchResp.success();
    }

}
